package com.beaut.project.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.beaut.project.util.ServletUtility;

public class RequestFilter implements Filter{
	// 编码
	protected String encoding = null;
	@Override
	public void destroy() {
		this.encoding = null;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpSession session = ((HttpServletRequest) request).getSession();
		boolean isValidSession =ServletUtility.isValidSession(session, "LOGIN_USER"); //进行session权限的验证 
		String qUri = ((HttpServletRequest) request).getRequestURI();
		
		if (!qUri.contains("springMVC") && qUri.endsWith("/")) {
			//针对菜单管理中配置的路径没有填写具体页面时，给一个默认的index.jsp
			qUri += "index.jsp";
		}
		if (qUri.endsWith(".jsp") && !ServletUtility.isLoginAction((HttpServletRequest) request)) {
			//如果访问的是页面，则判断该页面是否需要进行session检测,
			//比如用户直接访问登录页面时就不对其进行session有效性判断
			if (!isValidSession) {
				ServletUtility.forward("/public/sessionerror.jsp",
						(HttpServletRequest) request,
						(HttpServletResponse) response);
				return;
			}
		}
		
		request.setCharacterEncoding(encoding);
		response.setCharacterEncoding(encoding);
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		this.encoding = arg0.getInitParameter("encoding");
	}

}
